import QRCode from 'qrcodejs2'

/**
 * @type {import('@/types/global').createQRCode}
 */
export default (params) => {
  const { width, height, text, correctLevel = QRCode.CorrectLevel.L } = params
  return new Promise((resolve, reject) => {
    const div = document.createElement('div')
    const divId = 'div-QRCode'
    div.id = divId
    document.body.appendChild(div)
    try {
      const qr = new QRCode(divId, {
        text,
        width,
        height,
        correctLevel,
      })
      // 将 QR 码渲染到 Canvas
      const canvas = qr._el.querySelector('canvas');
      // 将 Canvas 转换为 Base64 编码
      const base64 = canvas.toDataURL('image/png');
      document.body.removeChild(document.getElementById(divId))
      resolve(base64)
    } catch (error) {
      // 使用 document.body.removeChild() 移除元素
      document.body.removeChild(document.getElementById(divId))
      resolve('')
    }
  })
}
